package com.huluobo.lc.ppjoke_jetpack.ui.home;

import android.os.UserManager;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.paging.DataSource;
import androidx.paging.ItemKeyedDataSource;

import com.alibaba.fastjson.TypeReference;
import com.huluobo.lc.libnetwork.ApiResponse;
import com.huluobo.lc.libnetwork.ApiService;
import com.huluobo.lc.libnetwork.JsonCallback;
import com.huluobo.lc.libnetwork.Request;
import com.huluobo.lc.ppjoke_jetpack.model.Feed;
import com.huluobo.lc.ppjoke_jetpack.ui.AbsViewModel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * DataSource:数据源
 * DataSource<Key,Value> key对应加载数据的条件信息,value对应数据实体类
 * PageKeyedDataSource<Key,Value> :适用于目标数据根据页信息请求数据的场景
 * ItemKeyedDataSource<Key,Value> :适用于目标数据的加载依赖特定item的信息,常用
 * PositionalDataSource<Key,Value> :适用于目标数据总数固定,通过特定的位置来加载数据
 */
public class HomeViewModel extends AbsViewModel<Feed> {

    private volatile boolean witchCache = true;

    @Override
    public DataSource createDataSource() {
        return dataSource;
    }

    ItemKeyedDataSource<Integer, Feed> dataSource = new ItemKeyedDataSource<Integer, Feed>() {
        @Override
        public void loadInitial(@NonNull LoadInitialParams<Integer> params,
                                @NonNull LoadInitialCallback<Feed> callback) {
            //加载初始化数据
            loadData(0, callback);
            witchCache = false;
        }

        @Override
        public void loadAfter(@NonNull LoadParams<Integer> params,
                              @NonNull LoadCallback<Feed> callback) {
            //加载分页数据的
            loadData(params.key, callback);
        }

        @Override
        public void loadBefore(@NonNull LoadParams<Integer> params,
                               @NonNull LoadCallback<Feed> callback) {
            callback.onResult(Collections.emptyList());
            //能够向前加载,一般用不到
        }

        @NonNull
        @Override
        public Integer getKey(@NonNull Feed item) {
            return item.id;
        }
    };

    private void loadData(int key, ItemKeyedDataSource.LoadCallback<Feed> callback) {
        ///feeds/queryHotFeedsList
        Request request =
                ApiService.get("/feeds/queryHotFeedsList").addParam("userId", 0).addParam("feedId"
                        , key).addParam("pageCount", 10).addParam("feedType", null).responseType(new TypeReference<ArrayList<Feed>>() {
        }.getType());//解析方式按照FeedBean来转换json
        if (witchCache) {
            request.cacheStrategy(Request.CACHE_ONLY);
            request.execute(new JsonCallback<List<Feed>>() {
                @Override
                public void onCacheSuccess(ApiResponse<List<Feed>> response) {
//                    if (response.body.size() != 0) {
                        Log.i("TagA", "onCacheSuccess");
//                    }
                }
            });
        }

        try {
            Request netRequest = witchCache ? request.clone() : request;
            netRequest.cacheStrategy(key == 0 ? Request.NET_CACHE : Request.NET_ONLY);
            ApiResponse<List<Feed>> response = netRequest.execute();
            List<Feed> data = response.body == null ? Collections.emptyList() : response.body;

            callback.onResult(data);

            if (key > 0) {
                //通过liveData发送数据,告诉UI层,是否应该主动关闭上拉加载的分页动画
                getBoundaryPageData().postValue(data.size() > 0);
            }
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

    }
}